<template>
    <el-dialog v-model="chartVisible" title="光照曲线可视化" width="80%">
    <div ref="chartDom" style="width: 100%; height: 500px;"></div>
    </el-dialog>
  <div class="electricity-container">
    <div class="form-section">
      <h2 class="title">外部电力市场</h2>

      <div class="input-group">
        <label class="input-label">典型电价曲线</label>
        <div class="input-controls">
          <!-- 编辑电价 -->
          <el-button plain @click="dialogFormVisible = true" class="distribution-btn">修改</el-button>
          <el-dialog v-model="dialogFormVisible" title="编辑电价" width="500">
            <el-form :model="form">
              <el-form-item
                v-for="i in 24"
                :key="i"
                :label="i.toString()"
                :label-width="formLabelWidth"
              >
                <el-input v-model="form[`name${i}`]" autocomplete="off" />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submitData">提交</el-button>
              </div>
            </template>
          </el-dialog>

          <!-- 可视化 -->

          <button @click="showChart" class="distribution-btn">
            <span class="btn-text">可视化</span>
          </button>

          <!-- 文件上传 -->
            <button @click="selectFile1" class="distribution-btn">
                <span class="btn-text"  >加载数据</span>
                <input
                  type="file"
                  ref="fileInput1"
                  @change="onFileChange1"
                  entityType="ShiChang"
                  style="display: none;"
                />
                <span class="file-name">solar_spring.txt</span>
            </button>(1-24)
        </div>
      </div>

      <el-dialog v-model="dialogVisible" title="文件内容" width="80%">
        <pre>{{ fileContent }}</pre>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage ,ElButton,ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

const selectFile1 = () => {
  fileInput1.value!.click()
}
const onFileChange1 = () => handleCsvUpload(fileInput1, 1)
const handleCsvUpload = async (
  fileInput: Ref<HTMLInputElement | null>,
  startId: number
) => {
  const file = fileInput.value?.files?.[0]
  if (!file) return

  const entityType = fileInput.value?.getAttribute('entityType') || ''
  if (!file.name.endsWith('.csv')) {
    ElMessageBox.alert('请选取 csv 文件！', '错误', {
      confirmButtonText: '确定',
      type: 'error',
      closeOnClickModal: false,
      callback: () => {
        if (fileInput.value) {
          fileInput.value.value = ''
        }
      }
    })
    return
  }

  const formData = new FormData()
  formData.append('file', file)

  let url = ''
  if (entityType === 'ShiChang') {
    url = `http://localhost:8080/shichang/upload/${startId}`
  }  else {
    ElMessage.error('未知的数据类型，无法上传')
    return
  }

  try {
    const res = await axios.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    ElMessageBox.alert(res.data.message || '上传成功', '成功', {
      confirmButtonText: '确定',
      type: 'success',
      closeOnClickModal: false,
      callback: () => {
        fileInput.value!.value = ''
      }
    })
  } catch (err: any) {
    const message = err.response?.data?.message || '上传失败'
    ElMessageBox.alert(message, '错误', {
      confirmButtonText: '确定',
      type: 'error',
      closeOnClickModal: false,
      callback: () => {
        fileInput.value!.value = ''
      }
    })
  }
}

const fileInput1 =  ref<HTMLInputElement | null>(null)



const chartVisible = ref(false)
const chartDom = ref<HTMLDivElement | null>(null)

const dialogFormVisible = ref(false)
const dialogVisible = ref(false)
const formLabelWidth = '50px'
interface DataItem {
  value: string | number;
}
const processShiChangData = (data: DataItem[]) => {
  const seasons = ['电价']
  const result: Record<string, number[]> = {}

  seasons.forEach((season, idx) => {
    result[season] = data
      .slice(idx * 24, (idx + 1) * 24)
      .map(item => parseFloat(String(item.value)))
  })

  return result
}

// 显示图表函数
const showChart = async () => {
  try {
    // 获取所有数据
    const response = await axios.get('http://localhost:8080/shichang/all')
    const data = response.data

    // 处理数据
    const chartData = processShiChangData(data)

    // 显示图表
    chartVisible.value = true
    setTimeout(() => {  // 延迟确保DOM渲染
      const myChart = echarts.init(chartDom.value!)

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['电价']
        },
        xAxis: {
          type: 'category',
          data: Array.from({ length: 24 }, (_, i) => `${i}:00`)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '电价',
            type: 'line',
            data: chartData['电价'],
            smooth: true
          },
        ]
      }

      myChart.setOption(option)
    }, 100)
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}


const form = reactive(
  Object.fromEntries(Array.from({ length: 24 }, (_, i) => [`name${i + 1}`, '']))
)

const fileContent = ref('')



// 页面加载时获取远程数据
onMounted(async () => {
  try {
    const resList = await Promise.all(
      Array.from({ length: 96 }, (_, i) =>
        axios.get(`http://localhost:8080/shichang/${i + 1}`)
      )
    )
    for (let i = 0; i < resList.length; i++) {
      form[`name${i + 1}`] = resList[i].data.value.toString()
    }
  } catch (err) {
    ElMessage.error('加载远程数据失败')
    console.error(err)
  }
})


const submitData = async () => {
  try {
    for (let i = 1; i <= 24; i++) {
      const newValue = parseFloat(form[`name${i}`]) || 0;
      await axios.put(`http://localhost:8080/shichang/single/${i}`, { value: newValue });
    }
    ElMessage.success('外部电力市场数据更新成功');
    dialogFormVisible.value = false;
  } catch (error) {
    ElMessage.error('更新失败，请检查输入格式');
    console.error('更新异常:', error);
  }
};

</script>

<style scoped>
.electricity-container {
  background-color: #f8fafc;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
  border-radius: 14px;
  padding: 36px;
  max-width: 920px;
  margin: 0 auto;
  font-family: 'Inter', 'Segoe UI', system-ui, sans-serif;
  color: #1e293b;
}

.title {
  color: #4c1d95;
  text-align: center;
  margin-bottom: 32px;
  font-size: 28px;
  font-weight: 700;
  padding-bottom: 16px;
  border-bottom: 2px solid #7c3aed;
  letter-spacing: 0.5px;
}

.section-title {
  color: #475569;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e2e8f0;
}

.form-section, .info-section {
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 28px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.input-group {
  display: flex;
  margin-bottom: 18px;
  gap: 16px;
}

.input-label {
  min-width: 180px;
  font-weight: 500;
  color: #475569;
  padding-top: 10px;
}

.input-controls {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f8fafc;
  border-radius: 8px;
  padding: 2px;
}

.form-input {
  padding: 10px 16px;
  border: 1px solid #053676;
  border-radius: 6px;
  width: 80px;
  text-align: right;
  font-size: 15px;
  background: transparent;
  color: #1e293b;
}

.form-input.small {
  width: 100px;
}

.form-input:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(124, 58, 237, 0.2);
}

.unit {
  margin: 0 5px;
  color: #64748b;
  font-size: 14px;
  font-weight: 500;
}

.distribution-btn {
  background-color: #7c3aed;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
  height: 42px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;

}

.distribution-btn:hover {
  background-color: #6d28d9;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(124, 58, 237, 0.3);
}

.btn-text {
  font-size: 14px;
  line-height: 1.2;
}

.file-name {
  color: rgba(255, 255, 255, 0.8);
  font-size: 11px;
  font-style: italic;
  margin-top: 2px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 18px;
}

.info-card {
  background-color: #f8fafc;
  padding: 18px;
  border-radius: 10px;
  border-left: 4px solid #7c3aed;
  transition: transform 0.2s, box-shadow 0.2s;
}

.info-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.info-label {
  display: block;
  font-weight: 500;
  color: #475569;
  margin-bottom: 10px;
  font-size: 15px;
}

.info-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-value {
  font-weight: 600;
  color: #4c1d95;
  font-size: 15px;
  white-space: nowrap;
}

@media (max-width: 768px) {
  .electricity-container {
    padding: 24px;
    border-radius: 0;
  }

  .input-group {
    flex-direction: column;
    gap: 8px;
  }

  .input-label {
    min-width: auto;
    padding-top: 0;
    margin-bottom: 6px;
  }

  .input-controls {
    width: 100%;
  }

  .form-input {
    width: 100%;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>

